package com.woniu.learnfile.utils;

import java.io.*;

/**
 * created  by woniu201
 * created in 2018/3/15
 */
public class FileUtil {

    public boolean writeFile(String path, String fileName, byte[] fileData)
    {
        //写文件
        File file = new File(path+ "\\" +fileName);
        if (file.exists()){
            System.out.println("文件已存在，先删除源文件，保留新文件");
            file.delete();
        }
        FileOutputStream fos;
        BufferedOutputStream bos;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(fileData);

            bos.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public byte[] readFile(String filePath , String fileName){

        File file = new File(filePath+ "\\" +fileName);
        if (!file.exists()) {
            System.out.println("文件不存在!");
            return null;
        }
        byte[] fileBytes = new byte[(int)file.length()];

        FileInputStream fis = null;
        BufferedInputStream bis = null;

        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            bis.read(fileBytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileBytes;
    }
}
